import { InjectionKey } from 'vue'
import { createStore, useStore as baseUseStore, Store } from 'vuex'
import { IUserInfo, IMenu } from '@/api/types/common'
import createPersistedState from 'vuex-persistedstate'
import { getItem, setItem } from '@/utils/storage'
import { USER } from '@/utils/constant'

const state = {
  isCollapse: false,
  user: getItem<{ token: string } & IUserInfo>(USER),
  menus: [] as IMenu[]
}

export type State = typeof state

// 定义 injection key
export const key: InjectionKey<Store<State>> = Symbol('store')

// Create a new store instance.
export const store = createStore<State>({
  plugins: [createPersistedState()], // ??
  state,
  mutations: {
    setIsCollapse (state, payload) {
      state.isCollapse = payload
    },
    setUser (state, payload) {
      state.user = payload
      // 持久化处理
      setItem(USER, state.user)
    },
    setMenus (state, payload) {
      state.menus = payload
    }
  }
})

// 定义自己的 `useStore` 组合式函数
export function useStore () {
  return baseUseStore(key)
}
